package controller

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"goproject/commonType"
	"goproject/logger"
	responseproxy "goproject/responseProxy"
	"io/ioutil"
	"net/http"
	"time"
)

func TestRspProxy(c *gin.Context) {
	log := logger.GetLogger()
	// 1. 设置 responseProxy 操作内容
	namespace := "sock-shop"
	servicename := "front-end"
	modifiedContent := commonType.StoredResponse{
		StatusCode: 200,
		Body: map[string]interface{}{
			"name":   "zyk",
			"age":    3,
			"sex":    "女",
			"height": "138cm",
		},
	}
	// 2. 调用 ApplyEnvoyFilter 返回 filtername
	filterName, err := responseproxy.ApplyEnvoyFilter(namespace, servicename, modifiedContent)
	if err != nil {
		log.Errorf("应用 EnvoyFilter 失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "应用 EnvoyFilter 失败"})
		return
	}
	defer func() {
		// 5. 删除 EnvoyFilter
		err := responseproxy.DeleteEnvoyFilter(namespace, filterName)
		if err != nil {
			log.Errorf("删除 EnvoyFilter 失败: %v", err)
		}
	}()
	time.Sleep(5 * time.Second)
	// 3. 定义并发起 HTTP 请求
	url := "http://127.0.0.1:30001/orders"
	method := "POST"
	payload := bytes.NewBufferString(`{}`)
	req, err := http.NewRequest(method, url, payload)
	if err != nil {
		log.Errorf("创建 HTTP 请求失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建 HTTP 请求失败"})
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Cookie", "md.sid=s%3AhuJg8orTMOP-BLFtZBYQ59Yapw-3x6Fl.LiULgSfwLw0b9%2FdbttxMsOFvlZnAeOKvRgxzZcn%2BTZQ; logged_in=huJg8orTMOP-BLFtZBYQ59Yapw-3x6Fl")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		log.Errorf("发起 HTTP 请求失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "发起 HTTP 请求失败"})
		return
	}
	defer resp.Body.Close()

	// 4. 收集响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Errorf("读取响应内容失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "读取响应内容失败"})
		return
	}

	// 6. 返回响应内容
	c.Data(resp.StatusCode, resp.Header.Get("Content-Type"), body)
}
